package com.smart.four.ioc.lifecycle.beanfactory;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * 测试bean生命周期
 *
 * @author junrui.wang
 * @create 2018/5/28
 */
public class BeanLifeCycle {
    private static void LifeCycleInBeanFactory(){
        //加载文件
        Resource res = new ClassPathResource("com/smart/four/ioc/lifecycle/beanfactory/beans.xml");
        BeanFactory bf = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((DefaultListableBeanFactory)bf);
        reader.loadBeanDefinitions(res);

        //向容器中注册MyBeanPostProcessor后处理器
        ((DefaultListableBeanFactory) bf).addBeanPostProcessor(new MyBeanPostProcessor());

        //向容器中注册MyInstantiationAwareBeanPostProcessor后处理器
        ((DefaultListableBeanFactory) bf).addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());


        //第一次从容器中获取car，将触发容器实例化bean，这将引发bean生命周期方法的调用
        Car car1 = (Car) bf.getBean("car");
        car1.introduce();
        car1.setColor("红色");

        //第二次从容器中获取car，直接从缓存池获取
        Car car2 = (Car) bf.getBean("car");

        //查看car1和car2是否指向同一地址（引用）
        System.out.println("car1==car2" + (car1==car2));

        ((DefaultListableBeanFactory) bf).destroySingletons();
    }

    public static void main(String[] args) {
        BeanLifeCycle.LifeCycleInBeanFactory();
    }

}
